package com.baidu.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创作时间：2019/12/17 10:20
 * 作者：李增强
 */
public class MyFilter implements Filter {
    List<String> notcheckurl = new ArrayList<String>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String exceptUrls = filterConfig.getInitParameter("exceptUrls");
        for (String noturl:exceptUrls.split(",")){
            notcheckurl.add(noturl.trim());
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String url = req.getRequestURI();
        url = url.substring(url.lastIndexOf("/")+1);
        if(notcheckurl.contains(url)){
            chain.doFilter(request, response);
        }else{
            Object ub = req.getSession().getAttribute("ub");
            if(ub!=null){
                chain.doFilter(request, response);
            }else{
                req.setAttribute("msg", "兄弟啊，没有登录是不能访问的！");
                req.getRequestDispatcher("/index.jsp").forward(req, response);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
